<template>
  <div class="header-search">
    <el-tooltip content="全局搜索" effect="dark" placement="bottom">
      <el-popover
        placement="bottom"
        width="300"
        trigger="click"
        @show="handleShow"
        @hide="handleHide"
      >
        <el-input
          ref="searchInput"
          v-model="search"
          placeholder="搜索菜单"
          class="search-input"
          prefix-icon="el-icon-search"
          clearable
          @keyup.enter.native="handleSelect"
          @input="handleInput"
        />
        <el-scrollbar class="search-results" v-show="searchPool.length > 0">
          <el-autocomplete
            ref="autoComplete"
            v-model="search"
            :fetch-suggestions="querySearch"
            placeholder="搜索菜单"
            class="search-autocomplete"
            :trigger-on-focus="false"
            @select="handleSelect"
            style="width: 100%"
          >
            <template slot-scope="{ item }">
              <div class="search-item">
                <i :class="item.meta.icon"></i>
                <span>{{ item.meta.title }}</span>
              </div>
            </template>
          </el-autocomplete>
          <div class="search-item" v-for="(item, index) in filteredSearchPool" :key="index" @click="handleSelect(item)">
            <i :class="item.meta.icon"></i>
            <span>{{ item.meta.title }}</span>
          </div>
        </el-scrollbar>
        <div slot="reference" class="search-icon">
          <i class="el-icon-search" />
        </div>
      </el-popover>
    </el-tooltip>
  </div>
</template>

<script>
// 移除Node.js的path模块导入
// import path from 'path'
import { debounce } from '@/utils/index'

// 添加一个简单的路径解析函数
function resolvePath(basePath, path) {
  if (path.startsWith('/')) {
    return path
  }
  
  // 确保basePath以/结尾
  if (basePath !== '/' && !basePath.endsWith('/')) {
    basePath = basePath + '/'
  }
  
  return basePath + path
}

export default {
  name: 'HeaderSearch',
  data() {
    return {
      search: '',
      searchPool: [], // 搜索池
      filteredSearchPool: [], // 过滤后的搜索结果
      show: false
    }
  },
  computed: {
    routes() {
      // 优先从store获取路由，如果没有则使用router.options.routes
      return this.$store.getters.routes && this.$store.getters.routes.length > 0
        ? this.$store.getters.routes
        : this.$router.options.routes || []
    }
  },
  watch: {
    show(val) {
      if (val) {
        document.body.addEventListener('click', this.closeSearch)
      } else {
        document.body.removeEventListener('click', this.closeSearch)
      }
    }
  },
  mounted() {
    this.initSearchPool()
  },
  beforeDestroy() {
    document.body.removeEventListener('click', this.closeSearch)
  },
  methods: {
    initSearchPool() {
      // 初始化搜索池
      const searchPool = []
      
      // 递归获取所有路由
      const generateRoutes = (routes, basePath = '/') => {
        if (!routes || !Array.isArray(routes)) return
        
        routes.forEach(route => {
          if (!route || route.hidden) return
          
          // 构建路由路径
          // 使用自定义的resolvePath函数替代path.resolve
          let routePath = resolvePath(basePath, route.path || '')
          
          // 如果是外部链接，直接使用
          if (route.path && /^(https?:|mailto:|tel:)/.test(route.path)) {
            routePath = route.path
          }
          
          // 如果有meta和title，添加到搜索池
          if (route.meta && route.meta.title) {
            searchPool.push({
              path: routePath,
              name: route.name,
              meta: { ...route.meta }
            })
          }
          
          // 递归处理子路由
          if (route.children && Array.isArray(route.children)) {
            generateRoutes(route.children, routePath)
          }
        })
      }
      
      generateRoutes(this.routes)
      this.searchPool = searchPool
    },
    handleInput: debounce(function() {
      if (!this.search || this.search.trim() === '') {
        this.filteredSearchPool = []
        return
      }
      
      this.filteredSearchPool = this.searchPool.filter(item => {
        return item && item.meta && item.meta.title && 
          item.meta.title.toLowerCase().indexOf(this.search.toLowerCase()) > -1
      })
    }, 300),
    querySearch(queryString, cb) {
      if (!queryString) {
        cb([])
        return
      }
      
      const results = this.searchPool.filter(item => {
        return item && item.meta && item.meta.title && 
          item.meta.title.toLowerCase().indexOf(queryString.toLowerCase()) > -1
      })
      
      cb(results || [])
    },
    handleSelect(item) {
      if (!item || !item.path) return
      
      this.search = ''
      this.show = false
      this.$nextTick(() => {
        // 避免导航到当前路径
        if (this.$route.path !== item.path) {
          this.$router.push(item.path).catch(err => {
            // 忽略NavigationDuplicated错误
            if (err.name !== 'NavigationDuplicated') {
              console.error(err)
            }
          })
        }
      })
    },
    handleShow() {
      this.show = true
      this.$nextTick(() => {
        this.$refs.searchInput.focus()
      })
    },
    handleHide() {
      this.show = false
      this.search = ''
      this.filteredSearchPool = []
    },
    closeSearch(e) {
      if (!this.$el.contains(e.target)) {
        this.show = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.header-search {
  display: inline-block;
  
  .search-icon {
    cursor: pointer;
    font-size: 18px;
    vertical-align: middle;
    
    &:hover {
      color: #409EFF;
    }
  }
  
  .search-input {
    width: 100%;
    margin-bottom: 10px;
  }
  
  .search-results {
    max-height: 300px;
    overflow-y: auto;
    
    .search-item {
      padding: 8px 15px;
      cursor: pointer;
      display: flex;
      align-items: center;
      
      i {
        margin-right: 10px;
        font-size: 16px;
      }
      
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}
</style> 